package com.example.shopping.user.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.example.shopping.R;
import com.example.shopping.app.LoginActivity;
import com.example.shopping.app.MyApplication;
import com.example.shopping.app.MySellerActivity;
import com.example.shopping.base.BaseFragment;
import com.example.shopping.bean.Response;
import com.example.shopping.bean.User;
import com.example.shopping.app.LocationActivity;
import com.example.shopping.utils.Constants;
import com.google.gson.Gson;
import com.hankkin.gradationscroll.GradationScrollView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.MediaType;

// 个人中心页面
public class UserFragment extends BaseFragment {

    @BindView(R.id.rl_person_header)
    RelativeLayout rlPersonHeader;
    @BindView(R.id.sv_person)
    GradationScrollView svPerson;
    @BindView(R.id.tv_usercenter)
    TextView tvUsercenter;

    @BindView(R.id.user_location)
    TextView user_location;
    @BindView(R.id.user_collect)
    TextView user_collect;
    @BindView(R.id.user_setting)
    TextView user_setting;

    @BindView(R.id.user_logout)
    TextView user_logout;

    @BindView(R.id.user_my_seller)
    LinearLayout user_my_seller;


    private User me = MyApplication.getMe();

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_user, null);
        ButterKnife.bind(this, view);


        user_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), LocationActivity.class));
            }
        });

        // 修改用户信息功能
        user_setting.setOnClickListener(new View.OnClickListener() {
            // 弹出框
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.user_info_dialog, null);
                EditText userName = view.findViewById(R.id.user_userName);
                userName.setText(me.getUserName());
                EditText phone = view.findViewById(R.id.user_phone);
                phone.setText(me.getPhone());
                EditText email = view.findViewById(R.id.user_email);
                email.setText(me.getEmail());
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("用户信息").setIcon(android.R.drawable.ic_dialog_info).setView(view);

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String updateName = userName.getText().toString();
                        String updatePhone = phone.getText().toString();
                        String updateEmail = email.getText().toString();

                        User updateUser = new User();
                        updateUser.setId(me.getId());
                        updateUser.setUserName(updateName);
                        updateUser.setPhone(updatePhone);
                        updateUser.setEmail(updateEmail);
                        HashMap<String, Object> jsonString = new HashMap<>();
                        jsonString.put("user",updateUser);
                        OkHttpUtils
                                .postString()
                                .url(Constants.User_update)
                                .content(new Gson().toJson(jsonString))
                                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                                .build()
                                .execute(new StringCallback() {


                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Log.e("updateLocation",e.getMessage());
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        if(response != null) {
                                            Response result = JSON.parseObject(response, Response.class);

                                            if(result.getCode() == 200000){
                                                Toast.makeText(mContext,result.getMessage(),Toast.LENGTH_SHORT).show();
                                                me.setUserName(updateName);
                                                me.setPhone(updatePhone);
                                                me.setEmail(updateEmail);
                                            }
                                        }
                                    }
                                });
                    }
                });
                builder.show();

            }
        });


        // 绑定退出功能
        user_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("是否退出登录？").setIcon(android.R.drawable.ic_dialog_info);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent_login = new Intent();
                        intent_login.setClass(mContext, LoginActivity.class);
                        intent_login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //关键的一句，将新的activity置为栈顶
                        startActivity(intent_login);
                        getActivity().finish();
                    }
                });
                builder.show();
            }
        });


        user_my_seller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MySellerActivity.class);
                startActivity(intent);
            }
        });

        return view;
    }

    @Override
    public void initData() {
        super.initData();

        ViewTreeObserver vto = rlPersonHeader.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private int height;

            @Override
            public void onGlobalLayout() {
                // 移除监听
                tvUsercenter.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                // 获取顶部图片的高度
                height = rlPersonHeader.getHeight();

                // 监听滑动，改变透明度
                svPerson.setScrollViewListener(new GradationScrollView.ScrollViewListener() {
                    @Override
                    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {

                        if (y <= 0) {   //设置标题的背景颜色
                            tvUsercenter.setBackgroundColor(Color.argb((int) 0, 255, 0, 0));
                        } else if (y > 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                            float scale = (float) y / height;
                            float alpha = (255 * scale);
                            tvUsercenter.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                            tvUsercenter.setBackgroundColor(Color.argb((int) alpha, 255, 0, 0));
                        } else {    //滑动到banner下面设置普通颜色
                            tvUsercenter.setBackgroundColor(Color.argb((int) 255, 255, 0, 0));
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
